package com.example.experiment4

import kotlin.random.Random

data class Card(
    val id: Int,
    val symbol: String,
    var isFaceUp: Boolean = false,
    var isMatched: Boolean = false
)

class GameModel(symbols: List<String>) {
    val cards: MutableList<Card>
    var moves: Int = 0
        private set
    var matches: Int = 0
        private set

    init {
        // 创建成对卡片并洗牌
        val pairList = symbols.flatMapIndexed { index, s ->
            listOf(Card(index * 2, s), Card(index * 2 + 1, s))
        }.toMutableList()
        pairList.shuffle(Random(System.currentTimeMillis()))
        cards = pairList
    }

    private var pendingIndex: Int? = null

    fun flip(position: Int): FlipResult {
        if (position < 0 || position >= cards.size) return FlipResult.None
        val card = cards[position]
        if (card.isMatched || card.isFaceUp) return FlipResult.None

        card.isFaceUp = true
        val prev = pendingIndex
        if (prev == null) {
            pendingIndex = position
            return FlipResult.First
        }

        moves += 1
        val prevCard = cards[prev]
        return if (prevCard.symbol == card.symbol) {
            prevCard.isMatched = true
            card.isMatched = true
            pendingIndex = null
            matches += 1
            FlipResult.Match
        } else {
            // 不匹配，稍后由控制器翻回去
            val a = prev
            val b = position
            pendingIndex = null
            FlipResult.Mismatch(a, b)
        }
    }

    fun allMatched(): Boolean = matches * 2 == cards.size

    fun currentScore(): Int {
        // 简单得分：匹配数*10 - 步数
        return (matches * 10 - moves).coerceAtLeast(0)
    }
}

sealed class FlipResult {
    data object None : FlipResult()
    data object First : FlipResult()
    data object Match : FlipResult()
    data class Mismatch(val first: Int, val second: Int) : FlipResult()
}


